import { defineComponent, ref, onMounted, onBeforeUnmount, Transition } from 'vue';
import './ToastStyles.css';

// 定义Toast组件
const ToastMessage = defineComponent({
  name: 'ToastMessage',
  props: {
    // 消息文本
    message: {
      type: String,
      default: ''
    },
    // 显示时间，单位毫秒
    duration: {
      type: Number,
      default: 3000
    },
    // 类型：success, error, warning, info
    type: {
      type: String,
      default: 'info',
      validator: (value) => ['success', 'error', 'warning', 'info'].includes(value)
    },
    // 位置：top, bottom, top-left, top-right, bottom-left, bottom-right
    position: {
      type: String,
      default: 'top',
      validator: (value) => [
        'top', 'bottom', 'top-left', 'top-right', 'bottom-left', 'bottom-right'
      ].includes(value)
    }
  },
  
  setup(props, { emit }) {
    // 控制Toast显示状态
    const visible = ref(false);
    // 定时器引用
    let timer = null;
    
    // 显示Toast
    const show = () => {
      visible.value = true;
      
      if (props.duration > 0) {
        // 设置自动关闭定时器
        timer = setTimeout(() => {
          hide();
        }, props.duration);
      }
    };
    
    // 隐藏Toast
    const hide = () => {
      visible.value = false;
      emit('close');
    };
    
    // 组件挂载时显示Toast
    onMounted(() => {
      show();
    });
    
    // 组件卸载前清除定时器
    onBeforeUnmount(() => {
      if (timer) {
        clearTimeout(timer);
      }
    });
    
    // 获取图标
    const getIcon = () => {
      switch (props.type) {
        case 'success':
          return '✅';
        case 'error':
          return '❌';
        case 'warning':
          return '⚠️';
        case 'info':
        default:
          return 'ℹ️';
      }
    };
    
    // 获取位置样式类
    const getPositionClass = () => {
      return `toast-${props.position}`;
    };
    
    // 渲染函数
    return () => ( 
      <Transition name="toast-fade">
        {visible.value && (
          <div 
            class={['toast', `toast-${props.type}`, getPositionClass()]}
            onClick={hide}
          >
            <span class="toast-icon">{getIcon()}</span>
            <span class="toast-message">{props.message}</span>
          </div>
        )}
      </Transition>
    );
  }
});

// 管理Toast实例的队列
const toastQueue = [];

// 安全地移除DOM节点的辅助函数
const safeRemoveElement = (element) => {
  if (element && element.parentNode) {
    element.parentNode.removeChild(element);
    return true;
  }
  return false;
};

// 创建Toast实例的工厂函数
const createToast = (options) => {
  const { createApp } = require('vue');
  
  // 创建挂载点
  const mountNode = document.createElement('div');
  document.body.appendChild(mountNode);
  
  // 创建应用实例
  const app = createApp({
    render() {
      return <ToastMessage {...options} onClose={() => {
        // 关闭后移除DOM
        setTimeout(() => {
          app.unmount();
          safeRemoveElement(mountNode);
          // 从队列中移除
          const index = toastQueue.findIndex(item => item.mountNode === mountNode);
          if (index !== -1) {
            toastQueue.splice(index, 1);
          }
        }, 300); // 等待过渡动画结束
      }} />;
    }
  });
  
  // 挂载应用
  app.mount(mountNode);
  
  // 创建实例对象
  const instance = {
    mountNode,
    app,
    close: () => {
      app.unmount();
      safeRemoveElement(mountNode);
      // 从队列中移除
      const index = toastQueue.findIndex(item => item.mountNode === mountNode);
      if (index !== -1) {
        toastQueue.splice(index, 1);
      }
    }
  };
  
  // 添加到队列
  toastQueue.push(instance);
  
  return instance;
};

// 导出Toast方法
export const toast = {
  info(message, duration = 3000, position = 'top') {
    return createToast({ message, duration, type: 'info', position });
  },
  success(message, duration = 3000, position = 'top') {
    return createToast({ message, duration, type: 'success', position });
  },
  error(message, duration = 3000, position = 'top') {
    return createToast({ message, duration, type: 'error', position });
  },
  warning(message, duration = 3000, position = 'top') {
    return createToast({ message, duration, type: 'warning', position });
  },
  // 清除所有Toast
  clear() {
    toastQueue.forEach(instance => {
      instance.app.unmount();
      safeRemoveElement(instance.mountNode);
    });
    toastQueue.length = 0;
  }
};

// 导出组件
export default ToastMessage; 